<?php

class UserController extends BackendController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        $this->redirect(array('admin'));
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User();
        $model->setScenario('create');

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
            $avatar = CUploadedFile::getInstance($model, 'avatar');
            if(is_object($avatar)&&(get_class($avatar)==='CUploadedFile')) {
                $model->avatar = $avatar->name;
            }
            else {
                $model->avatar = 0;
            }
            
            $year = Yii::app()->request->getParam('year');
            $month = Yii::app()->request->getParam('month');
            $day = Yii::app()->request->getParam('day');
            $model->birthday = $year.'-'.$month.'-'.$day;
            $model->code = time() . mt_rand(5, 99999999);
            $model->status = $_POST['User']['status'];
            $model->gender = $_POST['User']['gender'];
            $model->role = $_POST['User']['role'];
            if($model->validate()) {
                $model->password = UserIdentity::genPassword($model->password);
                $model->repassword = $model->password;
                if(is_object($avatar)&&(get_class($avatar)==='CUploadedFile')) {
                    $model->avatar = time().mt_rand(5, 99999999).'_'.$avatar->name;
                }
                if($model->save()) {
                    if(is_object($avatar)&&(get_class($avatar)==='CUploadedFile')) {
                        $imageUrl = Yii::app()->basePath.'/../data/avatar/'.$model->avatar;
                        $avatar->saveAs($imageUrl);
                        $image = Yii::app()->image->load($imageUrl);
                        $image->resize(200,200);
                        $image->save();
                    }
                    $this->redirect(array('admin'));
                }
            }
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
        $model->setScenario('update');
        $birthday = explode('-', $model->birthday);

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
		    $password = $model->password;
			$model->attributes=$_POST['User'];
            $avatar = CUploadedFile::getInstance($model, 'avatar');
            $year   = Yii::app()->request->getParam('year');
            $month  = Yii::app()->request->getParam('month');
            $day    = Yii::app()->request->getParam('day');
            $model->birthday = $year.'-'.$month.'-'.$day;
            $model->code = time() . mt_rand(5, 99999999);
            $model->status = $_POST['User']['status'];
            $model->gender = $_POST['User']['gender'];
            $model->role = $_POST['User']['role'];
            
            if($_POST['User']['password'] != '') {
                $password = UserIdentity::genPassword($_POST['User']['password']);
            }
            
            if($model->validate()) {
                $model->password = $password;
                $model->repassword = $password;
                if(is_object($avatar)&&get_class($avatar)==='CUploadedFile') {
                    if(is_file(Yii::app()->basePath.'/../data/avatar/'.$model->avatar)) {
                        unlink(Yii::app()->basePath.'/../data/avatar/'.$model->avatar);
                    }
                    $model->avatar = time().mt_rand(5, 99999999).'_'.$avatar->name;
                    if($model->save()) {
                        $imageUrl = Yii::app()->basePath.'/../data/avatar/'.$model->avatar;
                        $avatar->saveAs($imageUrl);
                        $image = Yii::app()->image->load($imageUrl);
                        $image->resize(200,200);
                        $image->save();
                        $this->redirect(array('admin'));
                    }
                }
                else {
                    if($model->save())
                        $this->redirect(array('admin'));
                }
            }
		}
        
        $model->password = '';
		$this->render('update',array(
			'model'=>$model,
            'birthday'=>$birthday,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);
        if(is_file(Yii::app()->basePath.'/../data/avatar/'.$model->avatar)) {
            unlink(Yii::app()->basePath.'/../data/avatar/'.$model->avatar);
        }
        $model->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
	    $this->redirect(array('admin'));
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
        
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
    
    /**
     * Profile User
     */
    public function actionProfile() {
        $model = $this->loadModel(Yii::app()->user->id);
        $birthday = explode('-', $model->birthday);
        
        // uncomment the following code to enable ajax-based validation
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-profile-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        if(isset($_POST['User'])) {
            $model->attributes = $_POST['User'];
            print_r($model->fullname);
            $avatar = CUploadedFile::getInstance($model, 'avatar');
            $year   = Yii::app()->request->getParam('year');
            $month  = Yii::app()->request->getParam('month');
            $day    = Yii::app()->request->getParam('day');
            $model->birthday = $year.'-'.$month.'-'.$day;
            $model->code = time() . mt_rand(5, 99999999);
            $model->status = $_POST['User']['status'];
            $model->gender = $_POST['User']['gender'];
            $model->role = $_POST['User']['role'];
            
            if(is_object($avatar)&&get_class($avatar)==='CUploadedFile') {
                if(is_file(Yii::app()->basePath.'/../data/avatar/'.$model->avatar)) {
                    unlink(Yii::app()->basePath.'/../data/avatar/'.$model->avatar);
                }
                $model->avatar = time().mt_rand(5, 99999999).'_'.$avatar->name;
                if($model->update()) {
                    $imageUrl = Yii::app()->basePath.'/../data/avatar/'.$model->avatar;
                    $avatar->saveAs($imageUrl);
                    $image = Yii::app()->image->load($imageUrl);
                    $image->resize(200,200);
                    $image->save();
                    $this->redirect(array('admin'));
                }
                else
                    $this->redirect(array('admin'));
            }
            else {
                if($model->update())
                    $this->redirect(array('admin'));
            }
        }
        
        $this->render('profile',array(
            'model'=>$model,
            'birthday'=>$birthday,
        ));
    }
    
    /**
     * Change password
     */
    public function actionChangepassword() {
        $model=new User('changepassword');
    
        // uncomment the following code to enable ajax-based validation
        if(isset($_POST['ajax']) && $_POST['ajax']==='user-changepassword-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    
        if(isset($_POST['User'])) {
            $model->attributes=$_POST['User'];
            $data = $this->loadModel(Yii::app()->user->id);
            $oldPassword = UserIdentity::genPassword($model->oldpassword);
            
            if($oldPassword == $data->password) {
                $data->password = UserIdentity::genPassword($model->password);
                if($data->update('password'))
                    $this->redirect(array('profile'));
            }
            else {
                $model->addError('oldpassword', 'Mật khẩu cũ không chính xác');
            }
        }
        
        $this->render('changepassword',array('model'=>$model));
    }
    
    public function actionPublish($id) {
        $id = (int) $id;
        $status = (int) Yii::app()->request->getParam('status');
        $model = $this->loadModel($id);
        if($status == 1)
            $model->status = 0;
        else
            $model->status = 1;
        $model->update('status');
        $this->redirect(array('admin'));
    }
    
    public function actionAjaxdelete() {
        if(isset($_POST['chk'])) {
            foreach($_POST['chk'] as $id) {
                $model = $this->loadModel($id);
                if(is_file(Yii::app()->basePath.'/../data/avatar/'.$model->avatar)) {
                    unlink(Yii::app()->basePath.'/../data/avatar/'.$model->avatar);
                }
                $model->delete();
            }
        }
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
